package com.kx.file.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.kx.file.config.AlibabaOSSConfig;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * 阿里云OSS工具类
 * @Author Sun
 * @Date 2021/7/22 19:14
 */
public class AlibabaOSSUtil {

    /**
     * OSS的客户端
     */
    private static OSS ossClient=new OSSClientBuilder().build(
            "https://"+ AlibabaOSSConfig.END_POINT,
            AlibabaOSSConfig.ACCESS_KEY_ID,
            AlibabaOSSConfig.ACCESS_KEY_SECRET);

    /**
     * 获取上传文件的url
     * @param  fileName
     * @return  文件的url
     */
    public static String getUrl(String fileName){
        String uploadUrl="https://"+AlibabaOSSConfig.BUCKET_NAME+"."+AlibabaOSSConfig.END_POINT+"/"+fileName;
        return uploadUrl;
    }

    /**
     * 上传文件的方法，以文件的形式
     * @param fileName  文件名
     * @param file  需要上传的文件
     * @return  文件保存位置的url
     */
    public static String uploadFile(String fileName, File file){
        //创建PutObjectRequest对象
        PutObjectRequest putObjectRequest = new PutObjectRequest(AlibabaOSSConfig.BUCKET_NAME, fileName, file);
        //上传对象
        ossClient.putObject(putObjectRequest);
        return getUrl(fileName);
    }


    /**
     * 上传文件的方法，以流的形式
     * @param fileName  文件名
     * @param inputStream  需要上传文件的输入流
     * @return  文件保存位置的url
     */
    public static String uploadFile(String fileName, InputStream inputStream){
        //创建文件上传的请求对象
        PutObjectRequest putObjectRequest=new PutObjectRequest(AlibabaOSSConfig.BUCKET_NAME,fileName,inputStream);
        //文件上传
        ossClient.putObject(putObjectRequest);
        return getUrl(fileName);
    }

    public static void main(String[] args) throws FileNotFoundException {
//        String url=uploadFile("1.jpg",new File("C:\\Users\\孙晋超\\Pictures\\Saved Pictures\\1.jpg"));
        String url=uploadFile("1.jpg",new FileInputStream(new File("C:\\Users\\孙晋超\\Pictures\\Saved Pictures\\1.jpg")));
        System.out.println(url);
    }
}
